package com.java2001.controller;


import com.java2001.pojo.User;
import com.java2001.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userServiceImpl;

    /**
     * 跳转到用户列表页面
     *
     * @param model
     * @return userList
     */
    @RequestMapping("/users")
    public String toUsers(Model model) {

        List<User> userList = userServiceImpl.queryUserList();
        model.addAttribute("userList", userList);
        return "/user/users";
    }

    /**
     * 跳转到添加用户页面
     *
     * @return
     */
    @RequestMapping("/toAddUser")
    public String toAddUser() {

        return "/user/addUser";
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser/{username}")
    public String deleteUser(@PathVariable("username") String username) {

        userServiceImpl.deleteUser(username);
        return "redirect:/user/users";
    }

    /**
     * 跳转到修改用户界面
     *
     * @param username
     * @param model
     * @return
     */
    @RequestMapping("/toUpdateUser/{username}")
    public String toUpdateUser(@PathVariable("username") String username, Model model) {

        User user = userServiceImpl.queryUserById(username);

        model.addAttribute("user", user);

        return "user/updateUser";
    }


    /**
     * 修改普通用户 密码、角色
     * @param username
     * @param password
     * @param role
     * @return
     */
    @RequestMapping("/updateUser")
    public String updateUser(String username, String password, Integer role){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);

        userServiceImpl.updateUserById(user);
        return "redirect:/user/users";
    }

}
